//个人信息
import {ElMessage} from 'element-plus'
import {nanoid} from "nanoid";
import {useStore} from "vuex";
import {useRouter} from 'vue-router'
import {reactive, ref, onMounted} from 'vue'
import {checkPasswordApi, getUserInfoApi, modifyAdminInfoApi, updatePasswordApi} from '../axios/API'
import {base_url} from '../constant/baseConstant'


export default function () {
    const router = useRouter()
    let store = useStore()

    //返回上一页
    function goBack() {
        router.back()
    }

    //个人信息实体
    let userInfo = ref({})

    //获取用户信息
    const getUserInfo = () => {
        getUserInfoApi().then(
            response => {
                const {data} = response
                if (data.status + '' === '200') {
                    userInfo.value = data.info
                } else {
                    ElMessage.error('系统错误')
                }
            }
        )
    }

    //提交表单信息，修改信息
    const formSubmit = () => {
        modifyAdminInfoApi(userInfo.value).then(
            response => {
                const {data} = response
                if (data.status + '' === '200') {
                    ElMessage.success('修改成功')
                    //这个一定要放在这里面，否侧调用顺序会发生变化，原因未知
                    getUserInfo()
                } else {
                    ElMessage.error('修改失败，请联系管理员')
                }
            }
        )
    }

    //控制修改密码弹出框的开关
    let isChangePassword = ref(false)

    //密码信息
    let password = reactive({
        oldPassword: '',
        newPassword: '',
        repeat: '',
        code: ''
    })

    //旧密码校验规则
    const checkOldPassword = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请输入旧密码！'))
        }
        //发送请求查看旧密码是否正确
        checkPasswordApi(password).then(
            response => {
                const {data} = response
                if (data.status + '' === '200') {
                    //校验通过
                    callback()
                } else {
                    //校验失败
                    console.log(data)
                    callback(new Error('密码错误！'))
                }
            }
        )
    }

    //重复密码校验规则
    const checkRepeat = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('请重复一遍密码！'))
        }
        if (value !== password.newPassword) {
            callback(new Error('两次密码不一致！'))
        }
        callback()
    }

    //校验规则
    let rules = reactive({
        oldPassword: [{validator: checkOldPassword, trigger: 'blur'}],
        newPassword: [{required: true, message: '请输入新密码', trigger: 'blur'}],
        repeat: [{validator: checkRepeat, trigger: 'blur'}],
        code: [{required: true, message: '验证码不能为空', trigger: 'blur'}],
    })

    //清除表单数据
    function clearPassword() {
        password.newPassword = ''
        password.oldPassword = ''
        password.code = ''
        password.repeat = ''
    }

    //定义表单ref
    let passwordForm = ref(null)

    //修改密码表单提交
    function updatePassword() {
        //校验表单验证项
        passwordForm.value.validate((valid) => {
            if (valid) {
                updatePasswordApi(password).then(
                    response => {
                        const {data} = response
                        if (data.status + '' === '200') {
                            ElMessage.success('保存成功，即将退出登录！')
                            //退出登录
                            store.commit('loginStore/UPDATE_TOKEN','')
                            router.push({name:'login'})
                        } else {
                            ElMessage.error(data.info)
                        }
                    }
                )
            } else {
                ElMessage.error('请正确输入表单内容！')
            }
        })
    }

    //页面加载时获取数据
    onMounted(() => {
        getUserInfo()
    })

    return {
        goBack, userInfo, formSubmit, isChangePassword, password, rules, clearPassword,
        captchaUrl: `${base_url}/admin/captcha?u=${nanoid()}`,
        updatePassword, passwordForm
    }
}
